package com.zyht.bank.manage.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.wx.model.BussinessException;
import com.wx.model.EnumCode;
import com.wx.model.ResObject;
import com.wx.util.FileUtil;
import com.wx.util.StringUtils;
import com.zyht.bank.entity.AxdCustLoan;
import com.zyht.bank.entity.AxdCustLoanExample;
import com.zyht.bank.entity.AxdCustLoanExample.Criteria;
import com.zyht.bank.entity.AxdOrgInfo;
import com.zyht.bank.entity.AxdOrgInfoExample;
import com.zyht.bank.manage.vo.AxdCertificateInfoVo;
import com.zyht.bank.manage.vo.OrgInfoVO;
import com.zyht.bank.service.AxdCertificateInfoService;
import com.zyht.bank.service.AxdCustLoanService;
import com.zyht.bank.service.AxdOrgInfoService;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.common.intercepter.Token;
import com.zyht.common.util.Page;
import com.zyht.website.entity.SysUser;

/**
* <p>Title:客户贷款信息后台管理 </p>
* <p>Description: </p>
* <p>Company: </p> 
* @author xgx
* @date 2017年7月4日
*/
@Controller
@RequestMapping("admin/loan2")
public class AdminLoanController extends AbsManageBaseController{
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Resource
	private AxdCustLoanService axdCustLoanService;
	@Resource
	private AxdOrgInfoService axdOrgInfoService;
	@Resource
	private AxdCertificateInfoService axdCertificateInfoService;
	
	@RequestMapping("index")
	@Token(save=true)
	public String index(@RequestParam(required=false) String custName,
            @RequestParam(required=false) String custIdNum,
			  @RequestParam(required=false) String custPhone,
			  @RequestParam(required=false) String code,
  			  @RequestParam(required=false,defaultValue="0") String isLoan,
  			@RequestParam(required=false,defaultValue="1") String isCheck,
  			  Integer currentPage,Model model,HttpServletRequest request){
		//获取用户是什么权限
		HttpSession session = request.getSession();
		SysUser sysUser = (SysUser) session.getAttribute(sessionUserKey);
		Integer orgId = sysUser.getOrgId();
		AxdOrgInfo axdOrgInfo = axdOrgInfoService.findOneById(orgId);
		if(null==axdOrgInfo){
			model.addAttribute("msg","此用户无权访问");
			model.addAttribute("redirect","admin/index");
			return "message";
		}
		Integer orgLevel = axdOrgInfo.getOrgLevel();
		
		
		AxdCustLoanExample example=new AxdCustLoanExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsDelEqualTo("0");
		if(!isLoan.equals("2")){
			criteria.andIsLoanEqualTo(isLoan);
		}
		if(!isCheck.equals("2")){
			criteria.andIsCheckEqualTo(isCheck);
		}
		if(StringUtils.isNotEmpty(custName)){
			  criteria.andCustNameLike("%"+custName+"%");
		 }
		if(StringUtils.isNotEmpty(custIdNum)){
			criteria.andCustIdNumLike("%"+custIdNum+"%");
		}
		if(StringUtils.isNotEmpty(custPhone)){
			criteria.andCustPhoneLike("%"+custPhone+"%");
		}
		if(StringUtils.isEmpty(code)){
			List<String> listCode=null;
			if(orgLevel==2){
				listCode=axdOrgInfoService.getOrgCodes(axdOrgInfo.getOrgCode());
				criteria.andLoanOrgCodeIn(listCode);
			}
			if(orgLevel==3){
				code=axdOrgInfo.getOrgCode();
				criteria.andLoanOrgCodeEqualTo(code);
			}
		}else{
			criteria.andLoanOrgCodeLike("%"+code+"%");
		}
		int total = axdCustLoanService.count(example);
		if(null==currentPage || currentPage==0){
			currentPage=1;
		}
		String pageSizeStr = PropertiesUtils.getConfig("paganation_page_size");
		int pageSize = Integer.valueOf(pageSizeStr);
		Page<AxdCustLoan> page = new Page<AxdCustLoan>(total,currentPage,pageSize);
		PageHelper.startPage(currentPage, pageSize);
		List<AxdCustLoan> list = axdCustLoanService.list(example);
		page.setRecordList(list);
		model.addAttribute("page",page);
	    model.addAttribute("custName",custName);
	    model.addAttribute("custIdNum",custIdNum);
	    model.addAttribute("isLoan",isLoan);
	    model.addAttribute("isCheck",isCheck);
	    model.addAttribute("custPhone",custPhone);
	    if(null!=code){
	    	AxdOrgInfoExample examples=new AxdOrgInfoExample();
			examples.createCriteria().andOrgCodeEqualTo(code);
			List<AxdOrgInfo> lists = axdOrgInfoService.list(examples);
			model.addAttribute("orgInfo",lists.get(0));
	    }
	    model.addAttribute("orgLevel",orgLevel);
		return "/banks/manage/custLoan/index";
	}
	
	@RequestMapping(value="custLoan{id}",method=RequestMethod.GET)
	@Token(save=true)
	public String redirectEditPage(@PathVariable("id") Integer id,Model model){
		AxdCustLoan axdCustLoan;
		if(null!=id){
			axdCustLoan=axdCustLoanService.findOneById(id);
			if(null!=axdCustLoan.getLoanOrgCode()){
				AxdOrgInfoExample example=new AxdOrgInfoExample();
				example.createCriteria().andOrgCodeEqualTo(axdCustLoan.getLoanOrgCode());
				List<AxdOrgInfo> list = axdOrgInfoService.list(example);
				model.addAttribute("orgInfo",list.get(0));
			}
		}else{
			axdCustLoan=new AxdCustLoan();
		}
		model.addAttribute("bean", axdCustLoan);
		return "/banks/manage/custLoan/edit";
	}
	
	@RequestMapping(value="persist",method=RequestMethod.POST)
	@Token(remove=true)
	public String saveOrUpdate(AxdCustLoan axdCustLoan,Model model){
		if(null!=axdCustLoan.getLoanId()){
			axdCustLoanService.updateById(axdCustLoan);
		}else{
			axdCustLoanService.addOne(axdCustLoan);
		}
		model.addAttribute("msg","操作成功");
		model.addAttribute("redirect","admin/loan/index");
		return "message";
	}
	//持久化修改
	@RequestMapping("rm")
	public @ResponseBody String remove(@RequestParam("ids") String ids, Model model){

		String[] idArray = ids.split(",");
		List<Integer> idList = new ArrayList<>();
		for (String id : idArray) {
			if(!"".equals(id)){
				idList.add(Integer.parseInt(id));
			}
		}
		if(idList.size()>0){
			axdCustLoanService.doBatchDelete(idList);
			return "success";
		}else{
			return "error";
		}
	} 
	//查询网点信息
	@RequestMapping("ins")
	public void institutionsInfo(String keyword, HttpServletRequest request,HttpServletResponse response){
		if(!StringUtils.isEmpty(keyword)){
			HttpSession session = request.getSession();
			SysUser sysUser = (SysUser) session.getAttribute(sessionUserKey);
			Integer orgId = sysUser.getOrgId();
			AxdOrgInfo axdOrgInfo = axdOrgInfoService.findOneById(orgId);
			AxdOrgInfoExample example = new AxdOrgInfoExample();
			example.createCriteria().andOrgNameLike("%"+keyword+"%");
			if(axdOrgInfo.getOrgLevel()==2){
				example.createCriteria().andPcodeEqualTo(axdOrgInfo.getOrgCode());
			}
			List<AxdOrgInfo> list = this.axdOrgInfoService.list(example);
			List<OrgInfoVO> insList = new ArrayList<>(list.size());
			for(AxdOrgInfo bean : list){
				OrgInfoVO vo = new OrgInfoVO();
				vo.setCode(bean.getOrgCode());
				vo.setName(bean.getOrgName());
				insList.add(vo);
			}
			String json = JSON.toJSONString(insList);
			writeJson(response,json);
		}else{
			writeJson(response,"");
		}
	}
	
	//文件的导入
	@RequestMapping("im")
	public String redirectUploadPage(){
		return "/banks/manage/custLoan/import";
	}
	
	@RequestMapping("import")
	public void doImport(MultipartFile file,HttpServletResponse response){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ResObject res = new ResObject();
		String msg = "";
		try {
			String relPath = FileUtil.writeLocalFile(file);
			if(relPath==null||relPath.isEmpty()){
				throw new BussinessException("写文件失败");
			}
			
			List<List<String>> cvs = FileUtil.readExcel(relPath);
			if(cvs.size()>500){
				throw new BussinessException("数据超过500条,会导致处理速度过慢,请分批上传");
			}
			if(cvs.size()<1){
				throw new BussinessException("数据行为空,请检查文件");
			}
			@SuppressWarnings("unchecked")
			List<String>[] cvsArray = cvs.toArray(new List[0]);
			
			List<String> list = new ArrayList<String>();
			List<AxdCustLoan> memberList = new ArrayList<AxdCustLoan>();
			for (int i = 1; i < cvsArray.length; i++) {
				List<String> list2 = cvsArray[i];
				String custName = StringUtils.isNull(list2.get(0));
				if(StringUtils.isEmpty(custName)){
					throw new BussinessException("数据行标"+(i+1)+"客户姓名不正确,请检查文件");
				}
				String custIdNum = StringUtils.isNull(list2.get(1));
				if(StringUtils.isEmpty(custIdNum)){
					throw new BussinessException("数据行标"+(i+1)+"身份证号不正确,请检查文件");
				}
				String custPhone =StringUtils.isNull(list2.get(2));
				if(StringUtils.isEmpty(custPhone)|| !StringUtils.isPhone(custPhone)){
					throw new BussinessException("数据行标"+(i+1)+"手机号不正确,请检查文件");
				}
				String isLoan =StringUtils.isNull(list2.get(3));
				String loanDate =StringUtils.isNull(list2.get(4));
				Date date=null;
				if(!StringUtils.isEmpty(loanDate)){
					date=format.parse(loanDate);
				}
				String isCheck =StringUtils.isNull(list2.get(5));
				String loanOrgCode =StringUtils.isNull(list2.get(6));
				
				AxdCustLoan axdCustLoan=new AxdCustLoan();
				axdCustLoan.setCustName(custName);
				axdCustLoan.setCustIdNum(custIdNum);
				axdCustLoan.setCustPhone(custPhone);
				axdCustLoan.setIsLoan(isLoan);
				axdCustLoan.setLoanDate(date);
				axdCustLoan.setIsCheck(isCheck);
				axdCustLoan.setLoanOrgCode(loanOrgCode);
				if(list.contains(custPhone)){
					throw new BussinessException("数据行标"+(i+1)+"手机号重复,请检查文件");
				}
				list.add(custPhone);
				memberList.add(axdCustLoan);
			}
			if(memberList==null || memberList.isEmpty()){
				throw new BussinessException("数据不正确,请检查文件");
			}
			//插入数据库
			axdCustLoanService.doBatchAdd(memberList);
			res.setCode(EnumCode.E0000);
			res.setMsg(msg);
			writeHtml(response,JSON.toJSONString(res));
			return;
		} catch (Exception e) {
			e.printStackTrace();
			if(e instanceof BussinessException){
				msg = e.getMessage();
			}
		}
		res.setMsg(msg);
		res.setCode(EnumCode.E1000);
		writeHtml(response,JSON.toJSONString(res));
		return;
	}
	
	
	//用途凭证
	@RequestMapping("certificate/{custIdNum}")
	public String certificate(@PathVariable("custIdNum") String custIdNum,Model model){
		List<AxdCertificateInfoVo> certificateInfos = axdCustLoanService.selectCertificateInfos(custIdNum);
		if(certificateInfos.size()<1){
			model.addAttribute("msg", "此用户没有上传任何凭证!");
		}else{
			model.addAttribute("certificateInfos", certificateInfos);
			model.addAttribute("custIdNum", custIdNum);
		}
		return "/banks/manage/custLoan/certificate";
	}
	
	//去凭证审核页面
	/*@RequestMapping("checkCertificate")
	public String checkCertificate(Integer id,Model model){
		AxdCertificateInfoWithBLOBs certificateInfo = axdCertificateInfoService.findOneById(id);
		model.addAttribute("certificateInfo", certificateInfo);
		return "/banks/manage/custLoan/check";
	}
	
	@RequestMapping(value="/checkUpdate",method=RequestMethod.POST)
	public void checkUpdate(AxdCertificateInfoWithBLOBs axdCustInfo,HttpServletResponse response){
		int update = axdCertificateInfoService.updateById(axdCustInfo);
		writeHtml(response, "<script type='text/javascript'>window.parent.closeWin('"+update+"')</script>");
	}*/
	

	
}
